#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "sqlite3.h"
#include "cgic.h"

#define N	64

char *errmsg;

int callback(void *para, int num, char **f_value, char **f_name)
{
	fprintf(cgiOut, "<tr>");
    int i;
	for(i = 0; i <num; i++)
	{
		fprintf(cgiOut, 		"<td height=\"30\" align=\"center\" valign=\"middle\" width=\"15%%\">%s</td>",f_value[i] );		
	}
	fprintf(cgiOut, 	"</tr>");
	return 0;
}





int cgiMain()
{
	char **resultp;
	int nrow, ncolumn, i, j, index;
	sqlite3 *data_db;
	

	
	
	
	
	cgiHeaderContentType("text/html"); 
	fprintf(cgiOut, "<HTML><HEAD>"); 
	fprintf(cgiOut, "<TITLE>当前实时数据</TITLE>");  
	fprintf(cgiOut, "<style type=\"text/css\"> body,td,th {font-size: 12px;margin-left: 0px;margin-top: 0px;}</style></HEAD>"); 
	fprintf(cgiOut, "<BODY BGCOLOR=\"#F8F9FA\">"); 
	
	fprintf(cgiOut, "<table width=\"100%%\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\">");
		
		// 信息表头
		fprintf(cgiOut, "<tr bgcolor=\"#DEE4E6\">");
		fprintf(cgiOut, 		"<td height=\"30\" align=\"center\" valign=\"middle\" width=\"15%%\">id</td>");
		fprintf(cgiOut, 		"<td height=\"30\" align=\"center\" valign=\"middle\" width=\"15%%\">time</td>");
		fprintf(cgiOut, 		"<td height=\"30\" align=\"center\" valign=\"middle\" width=\"15%%\">name</td>");
		fprintf(cgiOut, 		"<td height=\"30\" align=\"center\" valign=\"middle\" width=\"15%%\">operation</td>");
		fprintf(cgiOut, 	"</tr>");
	
	if(sqlite3_open("/login.db", &data_db) != SQLITE_OK)
	{
		
		printf( "<H1>%s</H1>", "Server is busy...\n");		
		return -1;
	}
	
	
	if(sqlite3_exec(data_db,  "select *from time", callback, NULL, &errmsg) != SQLITE_OK)
	{
		printf("err:%s\n", errmsg);
		exit(1);
	}
	

//	if(sqlite3_get_table(data_db, "select *from time", &resultp, &nrow, &ncolumn, &errmsg) != 0)
//	{
//		printf("get_table err\n");
//	}
//	index = ncolumn;
//	for(i = 0; i < nrow; i++)
//	{
//		fprintf(cgiOut, "<tr>");
//		for(j = 0; j<ncolumn; j++)
//		{
//			fprintf(cgiOut, 		"<td height=\"30\" align=\"center\" valign=\"middle\" width=\"15%%\">%s</td>",resultp[index++] );				
//		}
//		fprintf(cgiOut, 	"</tr>");
//	}
	
		sqlite3_close(data_db);
		fprintf(cgiOut, "</table>");
		fprintf(cgiOut, "<script type=\"text/jscript\">");
		fprintf(cgiOut, "setTimeout(\"self.close()\", 3000)");
		fprintf(cgiOut, "</script>");
		fprintf(cgiOut, "</BODY>"); 
		fprintf(cgiOut, "</HTML>");
		fflush(stdout);


	return 0;
}












